package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.common.exception.NameRepetitionException;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查找所有的分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 2、封装成树形结构
        List<CategoryEntity> levelOneMenu = entities.stream().filter(categoryEntity ->
            // 2.1 找到所有的一级分类
            categoryEntity.getParentCid() == 0
        ).map((oneMenu) ->{
            // 2.2 通过递归方法封装子节点
            oneMenu.setChildren(getChildren(oneMenu,entities));
            return oneMenu;
        }).sorted((menu1,menu2) -> {
            // 2.3 对一级分类排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return levelOneMenu;
    }

    /**
     * 根据id集合删除菜单
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 1、检查当前删除菜单，是否被其他地方引用
        System.out.println(asList);
        // 2、删除菜单
        baseMapper.deleteBatchIds(asList);

    }

    @Override
    public void saveCategory(CategoryEntity category) {
        // 先判断当前父分类下是否有改名字
        isRepetition(category);
        // 保存数据
        baseMapper.insert(category);
    }

    /**
     * 判断是重名
     * @param category
     */
    private void isRepetition(CategoryEntity category) {
        LambdaQueryWrapper<CategoryEntity> categoryEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryEntityLambdaQueryWrapper
                .eq(category.getParentCid() != null, CategoryEntity::getParentCid, category.getParentCid());
        List<CategoryEntity> entities = baseMapper.selectList(categoryEntityLambdaQueryWrapper);
        for (CategoryEntity entity : entities) {
            if (entity.getName().equals(category.getName())){
                throw new NameRepetitionException("要添加的分类名已存在");
            }
        }
    }

    @Override
    public void updateCateGory(CategoryEntity category) {

    }

    /**
     * 找到catelogId的完整路径
     * 格式：[父/子/孙子]
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogePath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        findParentPath(catelogId,path);
        // 将得到的结果返回
        Collections.reverse(path);
        return (Long[]) path.toArray(new Long[0]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Transactional
    @Override
    public void updateByCascade(CategoryEntity category) {
        isRepetition(category);
        baseMapper.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }

    }

    private void findParentPath(Long catelogId, List<Long> path){
        path.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0){
            findParentPath(categoryEntity.getParentCid(),path);
        }
    }

    /**
     * 递归查询所有子菜单
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> allList){

        List<CategoryEntity> entityList = allList.stream().filter(categoryEntity -> {
            // 1、遍历所有节点找到父节点Id等于rootId的节点
            return (categoryEntity.getParentCid()).equals(root.getCatId());
        }).map(categoryEntity -> {
            // 2、继续递归遍历
            categoryEntity.setChildren(getChildren(categoryEntity, allList));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            // 3、对当前节点进行排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return entityList;

    }

}